package com.apes.fn.business.fixedLoss.modle;

import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.plugin.soe.metadata.BusinessAttributeValue;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.Arith;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Category;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.model.ServeType;
import com.apes.scm.masterdata.stock.model.Location;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Map;

/**
 * @ClassName : LossQuotation
 * @Description : 定损报价单明细
 * @Author : WSJ
 * @Date: 2020-03-05 16:14
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = LossQuotationItem.CONST_TABLE_NAME)
public class LossQuotationItem extends Model {
    public final static String CONST_TABLE_NAME = "ser_loss_quotation_item";

    @Id
    @Column(name = "id", nullable = false, length = 24)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "定损报价单明细", padding = 4)
    @Comment("ID")
    private String id;

    @Column(name = "sort", length = 250)
    @Comment("排序字段")
    private String sort;

    @ManyToOne(optional = false)
    @JoinColumn(name = "loss_Quotation_id", referencedColumnName = "id")
    @Comment("定损报价单号")
    private LossQuotation lossQuotation;

    @Column(name = "higher_level_code", length = 24)
    @Comment("上级商品编码")
    private String higherLevelCode;


    @Column(name = "service", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    @Comment("服务")
    private boolean service = true;

    @Column(name = "agree", columnDefinition = ApesConst.FIELD_BOOLEAN_TRUE)
    @Comment("同意标识")
    private boolean agree = true;

    @Column(name = "plan", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    @Comment("已转定损方案")
    private boolean plan = false;

    @Column(name = "insurance", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    @Comment("保险")
    private boolean insurance = true;

    @Comment("提前修车")
    @Column(name = "advance_Repair", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    private boolean advanceRepair;

    @Column(name = "product_rule", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    @Comment("带安标记")
    private boolean productRule = false;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_id", referencedColumnName = "id")
    @Comment("商品")
    private Product product;

    @Column(name = "map_address", length = 4000)
    @Comment("商品图片")
    private String mapAddress;

    @Column(name = "tag_map_address", length = 4000)
    @Comment("图片地址-带标记")
    private String tagMapAddress;

    //Evaluation type
    @States(name = "评估类型", values = {
            @State(id = "A", name = "工时"),
            @State(id = "B", name = "配件"),
            @State(id = "C", name = "辅料")
    })
    @Comment("评估类型")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "evaluation_Type", referencedColumnName = "id")
    private BusinessAttributeValue evaluationType;


    @Transient
    @Comment("品类")
    private Category category ;
    public Category getCategory(){
        if(this.fitting != null) return  this.fitting;
        if(this.product != null) return this.product.getCategory();
        return null;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "fitting", referencedColumnName = "id")
    @Comment("配件")
    private Category fitting;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_uom_id", referencedColumnName = "id")
    @Comment("计量单位编码")
    private ProductUom uom;

    @Column(name = "sale_qty", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("销售数量")
    private double saleQty = 0;

    @Column(name = "require_Qty", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("要货数量")
    private double requireQty = 0;

    @Column(name = "receive_Qty", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("已要货数量")
    private double receiveQty = 0;


    @Column(name = "primary_price_unit", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("原销售单价")
    private double primaryPriceUnit = 0;

    @Column(name = "sale_Price", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("销售单价")
    private double salePrice = 0;

    @Column(name = "pft_price_unit", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("优惠单价")
    private double pftPriceUnit = 0;

    @Column(name = "sales_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("销售金额")
    private double salesAmount = 0;


    @Column(name = "floor_price", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("最低限价")
    private double floorPrice = 0;

    @Column(name = "minimum_Price", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("最低定损单价")
    private double minimumPrice = 0;

    @Column(name = "clerk_price_limmit", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("店员限价")
    private double clerkPriceLimit = 0;

    @Column(name = "shop_owner_price_limit", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("店长限价")
    private double shopOwnerPriceLimit = 0;

    @Column(name = "cso_price_limit", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("销售总监限价")
    private double csoPriceLimit = 0;

    @Column(name = "base_price", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("销售基准价")
    private double basePrice = 0;

    @Column(name = "discount_rate", nullable = false, columnDefinition = ApesConst.FIELD_ROUND_16_8)
    @Comment("折扣率")
    private double discountRate = 0;

    @Column(name = "platform_price_cost_in_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("平台成本单价")
    private double platformPriceCosInTax = 0;

    @Column(name = "price_cost_unit_in_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("含税成本单价")
    private double priceCostUnitInTax = 0;

    @Column(name = "price_cost_unit_ex_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("不含税成本单价")
    private double priceCostUnitExTax = 0;

    @Column(name = "supply_Chain_Management", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("供应链管理费用")
    private double supplyChainManagement = 0;

    @Column(name = "refer_Tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("参考成本")
    private double referTax = 0;

    @Column(name = "inner_refer_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("内协参考成本")
    private double innerReferTax = 0;

    @Column(name = "estimated_Commission", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("预估提成单价")
    private double estimatedCommission = 0;

    @Column(name = "fixed_Loss_Price", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("定损单价")
    private double fixedLossPrice = 0;

    @Column(name = "fixed_Loss_Amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("定损金额")
    private double fixedLossAmount = 0;

    @Column(name = "purchase_remarks", length = 250)
    @Comment("采购备注")
    private String purchaseRemarks;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "location_id", referencedColumnName = "id", nullable = false)
    @Comment("仓库库区")
    private Location location;

    @Column(name = "remarks", length = 256)
    @Comment("备注")
    private String remarks;

    @Column(name = "customer_Remarks", length = 256)
    @Comment("客服备注")
    private String customerRemarks;

    @Comment("服务方案单号")
    @Column(name = "service_Plan", length = 32)
    private String servicePlan;
    //
    // @ManyToOne(fetch = FetchType.LAZY)
    // @JoinColumn(name = "original_product_id", referencedColumnName = "id")
    // @Comment("原询价商品编码")
    // private Product originalInquiryProduct;
    //

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="serve_type_id", referencedColumnName = "id")
    @Comment("服务类型")
    private ServeType serveType;


    @Column(name = "old_inquiry_number", length = 32)
    @Comment("老框架询价单号")
    private String oldInquiryNumber;

    @Column(name = "carrier_id")
    @Comment("承运商编码")
    private String carrierId;

    @Column(name = "carrier_name")
    @Comment("承运商名称")
    private String carrierName;

    @Column(name = "inquiry_gooods_state", length = 32)
    @Comment("货源状态(0无货|1现货|2需订货)")
    private String inquiryGooodsState;
    //
    @Transient
    @Comment("询价类型(0:询库存;1:询价格)")
    private Integer inquiryType = 1;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "platform_id", referencedColumnName = "id")
    @Comment("平台")
    private PartyRole platform;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "original_product_id", referencedColumnName = "id")
    @Comment("原询价商品编码")
    private Product originalInquiryProduct;

    @Column(name = "part_code", length = 4000)
    @Comment("零件编码")
    private String partCode;
    @Column(name = "part_name", length = 4000)
    @Comment("零件名称")
    private String partName;

    @Comment("询价配件选择功能")
    @Column(name = "inquiry_select_flag", columnDefinition = "number(1,0) default 1")
    private Integer inquirySelectFlag = 1;

    @Column(name = "replace_With_Repair",columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    @Comment("以修代换标识")
    private boolean replaceWithRepair = false;

    @Column(name = "expected_arrival_time", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("预计到货时长")
    private double expectedArrivalTime = 0;

    @Column(name = "image_sn")
    @Comment("图号")
    private String imageSN;

    @Column(name = "price_forward")
    @Comment("渠道")
    private String priceForward;////1：价格前置标记 2：新平台询价 3：询价执行表 4：三头六臂 5：巴图鲁 6：外采

    @Comment("报价结果Id")
    @JoinColumn(name = "quote_result_id")
    private String quoteResultId;

    @Transient
    private Map addInfo;

    @Transient
    private String haveOffice = "暂无报价";
    public String getHaveOffice(){
        if ( "20".equals(this.product.getProductGroup().getId())) return "已有报价";
        return this.haveOffice;
    }

    @Column(name = "unique_value", length = 4000)
    @Comment("唯一值")
    private String uniqueValue;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplier_id", referencedColumnName = "id")
    @Comment("供应商")
    private PartyRole supplier; //供应商

    @Column(name = "fourS_Price", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("4s价格")
    private Double fourSPrice; // 4s价格

    @Transient
    private boolean needInquiry = true;

    @Transient
    private String inquirySource = "none";

    @Transient
    private double expectedArrivalTimeTemp;
    public double getExpectedArrivalTimeTemp(){
        if("2".equals(this.inquiryGooodsState)){
            return Arith.round(this.expectedArrivalTime / 24,3);
        }
        return 0;
    }

    /**
     * 换算销售数量
     * @return
     */
    @Transient
    private double salesVolume;
    public double getSalesVolume() {
        try {
            return uom.computeQty(saleQty, uom, false);
        }catch (Exception e){
            return this.saleQty;
        }
    }

    @Transient
    private String requireQtyTempState = "none";  // 无要货：none;未审核：create;已审核：approve;

    @Transient
    private String requireQtyId;  // 未审核要货单id

    @Transient
    private double requireQtyTemp = 0;

    public void addRequireQtyTemp(double requireQty){
        this.requireQtyTemp += requireQty;
    }

    public boolean checkExternalInquiry() {
        if (this.getOldInquiryNumber()!=null&&this.getOldInquiryNumber().startsWith("WC"))return true;
        return false;
    }
}
